package com.example.boot.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @description: jwt工具类
 * @author: mhpy
 * @date 2022/7/29 10:33
 */
public class JwtHelper {
    private static final long EXPIRE_TIME = 60 * 60 * 1000;

    public static String getUserToken(Integer id,String name) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token;
        // 将 name 保存到 token 里面
        token= JWT.create()
                .withAudience(name)
                //两千分钟后token过期
                .withExpiresAt(date)
                // 以 id 作为 token 的密钥
                .sign(Algorithm.HMAC256(String.valueOf(id)));
        return token;
    }
    //        String userToken = JwtHelper.getUserToken(user.getId(),user.getName());

    public static void main(String[] args) {
        String token = getUserToken(111,"123");
        System.out.println(token);
        DecodedJWT decode = JWT.decode(token);



        System.out.println(decode);
        System.out.println(decode.getHeader());
        System.out.println(decode.getPayload()+"payload");
        System.out.println(decode.getSignature());
        System.out.println(decode.getAlgorithm());
        System.out.println(decode.getAudience().get(0)+"+++");
        System.out.println(decode.getClaims().toString()+"claim");
        System.out.println(decode.getToken());
        System.out.println(decode.getType()+"type");
        System.out.println(decode.getId());
    }
}
